package com.safety.hat.service.impl.hat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.safety.hat.data.ACTEnum;
import com.safety.hat.data.Result;
import com.safety.hat.data.hat.HatSOSInfoBO;
import com.safety.hat.service.admin.adpater.IAdminSocketUserService;
import com.safety.hat.service.hat.adapter.IHatSocketSOSAdapterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.List;
import java.util.Objects;

/**
 * @Author: lijun
 * @Date: 2020/5/25 下午5:58
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class HatSocketSOSAdapterServiceImpl implements IHatSocketSOSAdapterService<HatSOSInfoBO> {

    private final IAdminSocketUserService adminSocketUserService;

    /**
     * 处理消息
     */
    @Override
    public void handleMessage(HatSOSInfoBO message, Session session) {
        if (Objects.nonNull(message)) {
            List<Session> serviceAllSessionList = adminSocketUserService.getAllSession();
            serviceAllSessionList.forEach(serverSession -> {
                JSON.toJSON(message);
                String jsonString = JSONObject.toJSONString(message);
                JSONObject jsonObject = JSON.parseObject(jsonString);
                jsonObject.put("cmd", ACTEnum.HAT_SOS.getAct());
                serverSession.getAsyncRemote().sendText(jsonObject.toJSONString());
            });
            Result<Object> result = Result.builder().cmd(ACTEnum.HAT_SOS.getAct()).status(true).msg("上报成功").build();
            session.getAsyncRemote().sendText(JSONObject.toJSONString(result));
        }
    }

    /**
     * 根据当前行为判断是否可以被处理
     */
    @Override
    public boolean canHandle(String act) {
        return ACTEnum.HAT_SOS.is(act);
    }


    /**
     * 获取设备ID
     */
    @Override
    public String getDeviceId(String message) {
        return transMessageToObject(message).getDeviceId();
    }

    @Override
    public Class getMessageClass() {
        return HatSOSInfoBO.class;
    }
}
